<template>
  <div class="loan-home-container">
    <!-- 顶部区域 -->
    <header class="header">
      <div class="header-title">
        <span>新一贷</span>
      </div>
      <div class="loan-info">
        <div class="amount-label">最高借款额度(元)</div>
        <div class="amount-value">300,000</div>
        <div class="loan-features">
          <div class="feature-item">
            <el-icon><Document /></el-icon>
            <span>纯线上申请</span>
          </div>
          <div class="feature-item">
            <el-icon><Timer /></el-icon>
            <span>最长借三年</span>
          </div>
          <div class="feature-item">
            <el-icon><Lightning /></el-icon>
            <span>秒级放款</span>
          </div>
        </div>
      </div>
    </header>

    <!-- 产品详情区域 -->
    <section class="product-info">
      <div class="info-item">
        <div class="info-label">最低日息</div>
        <div class="info-value">
          <span class="highlight">0.02%</span>
          <span class="original">0.06%</span>
        </div>
      </div>
      <div class="info-item">
        <div class="info-label">借款额度</div>
        <div class="info-value">¥20000~300000</div>
      </div>
      <div class="info-item">
        <div class="info-label">分期期限</div>
        <div class="info-value">可选3、6、12、24、36期</div>
      </div>
    </section>

    <!-- 申请金额区域 -->
    <section class="apply-amount">
      <div class="section-title">申请金额(元)</div>
      <div class="amount-display">{{ formatAmount(loanAmount) }}</div>
      
      <!-- 滑块区域 -->
      <div class="slider-container">
        <div class="min-amount">{{ formatAmount(minAmount) }}元</div>
        <div class="max-amount">{{ formatAmount(maxAmount) }}元</div>
        
        <div class="slider-controls">
          <button class="decrease-btn" @click="decreaseAmount" :disabled="loanAmount <= minAmount">
            <el-icon><Minus /></el-icon>
          </button>
          
          <div class="slider-track" ref="sliderTrack" @click="handleTrackClick">
            <div class="slider-fill" :style="{ width: fillWidth + '%' }"></div>
            <div 
              class="slider-handle" 
              :style="{ left: fillWidth + '%' }"
              @mousedown="startDrag"
              @touchstart="startDrag"
            >
              <div class="handle-inner"></div>
            </div>
          </div>
          
          <button class="increase-btn" @click="increaseAmount" :disabled="loanAmount >= maxAmount">
            <el-icon><Plus /></el-icon>
          </button>
        </div>
      </div>
    </section>

    <!-- 借款期限区域 -->
    <section class="loan-period">
      <h3 class="section-title">借款期限</h3>
      <div class="period-options">
        <button 
          v-for="period in periodOptions" 
          :key="period"
          class="period-btn"
          :class="{ active: selectedPeriod === period }"
          @click="selectPeriod(period)"
        >
          <span>{{ period }}</span>个月
        </button>
      </div>
    </section>

    <!-- 每期还款区域 -->
    <section class="repayment-info">
      <h3 class="section-title">每期还款</h3>
      <div class="repayment-details">
        <div class="repayment-amount">
          <i id="yuegong">{{ formatAmount(monthlyPayment) }}</i>元
        </div>
        <div class="repayment-rate">
          <span>&nbsp;&nbsp;(含日利率<span id="rixi">{{ dailyRate }}</span>% ￥<i id="fuwufei">{{ formatAmount(serviceFee) }}</i>元)</span>
        </div>
      </div>
    </section>

    <!-- 协议同意区域 -->
    <section class="agreement">
      <div class="agreement-checkbox">
        <el-checkbox v-model="agreePeriods">
          同意
          <a href="javascript:;" @click="showServiceAgreement">《用户服务协议》</a>
          <a href="javascript:;" @click="showLoanAgreement">《借款协议》</a>
        </el-checkbox>
      </div>
    </section>

    <!-- 申请按钮 -->
    <section class="apply-btn-section">
      <button 
        class="apply-btn" 
        :disabled="!agreePeriods || isSubmitting"
        @click="submitApplication"
      >
        立即申请
      </button>
    </section>

    <!-- 成功案例滚动区域 -->
    <section class="success-cases">
      <div class="marquee-container">
        <div class="marquee-content" ref="marqueeContent">
          <div v-for="(item, index) in displayCases" :key="index" class="case-item">
            <span class="case-date">{{ item.date }}</span>:
            <span class="case-phone">{{ item.phone }}</span>
            成功借款
            <span class="case-amount">{{ item.amount }}</span>元!
          </div>
        </div>
      </div>
    </section>

    <!-- 常见问题区域 -->
    <section class="faq-section">
      <div class="faq-item">
        <div class="faq-question">
          <span class="question-tag">Q1</span>
          <span class="question-text">新一贷的申请条件是什么？</span>
        </div>
        <div class="faq-answer">
          年龄在18~60岁的中国公民，均可申请。
        </div>
      </div>
      <div class="faq-item">
        <div class="faq-question">
          <span class="question-tag">Q2</span>
          <span class="question-text">我需要准备哪些资料？</span>
        </div>
        <div class="faq-answer">
          本人身份证、银行卡（仅用于放款）、手机号码。
        </div>
      </div>
      <div class="faq-item">
        <div class="faq-question">
          <span class="question-tag">Q3</span>
          <span class="question-text">借款后，如何还款</span>
        </div>
        <div class="faq-answer">
          新一贷支持每月还款日自动扣款，您也可以通过新一贷APP进行手动还款。
        </div>
      </div>
    </section>
    <section class="other">
        <a id="dnapp" href="javascript:;">
          <img src="../../assets/imgs/other.png" alt="" class="other-img">
        </a>
    </section>
    <!-- 公司信息 -->
    <section class="company-info">
      <div class="info-text">西安新一贷互联网科技有限公司</div>
      <div class="info-text">陕ICP备14003138号</div>
    </section>

    <!-- 底部导航栏 -->
    <bottom-nav-bar />

    <!-- 协议弹窗 -->
    <el-dialog
      v-model="showAgreement"
      :title="agreementTitle"
      width="90%"
      top="15vh"
    >
      <div class="agreement-content">
        <div v-if="agreementType === 'service'">
          <h3>用户服务协议</h3>
          <p>欢迎使用我们的贷款系统。在使用本系统之前，请仔细阅读以下条款。</p>
          <p>通过使用本系统，您同意遵守这些条款和条件。我们保留随时修改这些条款的权利。</p>
          <p>您的个人信息将按照我们的隐私政策进行处理和保护。</p>
        </div>
        <div v-else-if="agreementType === 'loan'">
          <h3>借款协议</h3>
          <p>本协议是您与贷款系统之间关于贷款服务的法律协议。</p>
          <p>您确认所提供的个人信息真实、准确、完整，并同意我们对您的信息进行审核。</p>
          <p>您同意按照约定的还款计划按时还款，如有逾期，将承担相应的违约责任。</p>
          <p>您有权在贷款发放前取消贷款申请，但一旦贷款发放，您需按照约定履行还款义务。</p>
          <p>本协议自您点击"同意"按钮并提交贷款申请时生效。</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAgreement">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore, useLoanStore } from 'store';
import { ElMessage, ElMessageBox } from 'element-plus';
import BottomNavBar from '../../components/BottomNavBar.vue';
import { 
  calculateMonthlyPayment, 
  calculateServiceFee, 
  dailyRateToMonthlyRate,
  formatAmount as formatAmountUtil
} from '../../utils/loanCalculator';
import { 
  Document, 
  Timer, 
  Lightning,
  Plus,
  Minus
} from '@element-plus/icons-vue';

// 路由
const router = useRouter();

// 用户状态
const userStore = useUserStore();
// 贷款状态
const loanStore = useLoanStore();
// 贷款金额相关
const minAmount = ref(20000);
const maxAmount = ref(300000);
const amountStep = ref(100);
const loanAmount = ref(loanStore.state.applyData.amount || 50000);

// 贷款期限相关
const periodOptions = ref([3, 6, 12, 24, 36]);
const selectedPeriod = ref(loanStore.state.applyData.period || 12);

// 还款计算相关
const dailyRate = ref(0.02);
const monthlyRate = computed(() => dailyRateToMonthlyRate(dailyRate.value));
const serviceFee = computed(() => calculateServiceFee(loanAmount.value, dailyRate.value));
const monthlyPayment = computed(() => {
  return calculateMonthlyPayment(loanAmount.value, monthlyRate.value, selectedPeriod.value);
});

// 协议相关
const agreePeriods = ref(false);
const showAgreement = ref(false);
const agreementType = ref('');
const agreementTitle = computed(() => {
  return agreementType.value === 'service' ? '用户服务协议' : '借款协议';
});

// 申请状态
const isSubmitting = ref(false);

// 成功案例数据
const successCases = ref([
  { date: '2023-09-24', phone: '151****6157', amount: '73200' },
  { date: '2023-09-24', phone: '138****4321', amount: '50000' },
  { date: '2023-09-23', phone: '159****7890', amount: '100000' },
  { date: '2023-09-23', phone: '136****5678', amount: '30000' },
  { date: '2023-09-22', phone: '187****2345', amount: '200000' }
]);

// 为了实现无缝滚动，我们需要复制足够的数据
const displayCases = computed(() => {
  // 复制3次数据以确保滚动效果流畅
  return [...successCases.value, ...successCases.value, ...successCases.value];
});

// 格式化金额
const formatAmount = (amount) => {
  if (typeof amount === 'number') {
    return formatAmountUtil(amount, 2).replace('.00', '');
  }
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 计算填充宽度百分比
const fillWidth = computed(() => {
  return ((loanAmount.value - minAmount.value) / (maxAmount.value - minAmount.value)) * 100;
});

// 增加金额
const increaseAmount = () => {
  if (loanAmount.value + amountStep.value <= maxAmount.value) {
    loanAmount.value += amountStep.value;
  } else {
    loanAmount.value = maxAmount.value;
    ElMessage.warning('不能大于最大金额');
  }
};

// 减少金额
const decreaseAmount = () => {
  if (loanAmount.value - amountStep.value >= minAmount.value) {
    loanAmount.value -= amountStep.value;
  } else {
    loanAmount.value = minAmount.value;
    ElMessage.warning('不能小于最小金额');
  }
};

// 处理轨道点击
const handleTrackClick = (event) => {
  if (!event.currentTarget) return;
  
  const trackRect = event.currentTarget.getBoundingClientRect();
  const clickPosition = event.clientX - trackRect.left;
  const trackWidth = trackRect.width;
  
  const percentage = clickPosition / trackWidth;
  const newValue = minAmount.value + percentage * (maxAmount.value - minAmount.value);
  
  // 按步长调整值
  const steps = Math.round((newValue - minAmount.value) / amountStep.value);
  loanAmount.value = minAmount.value + steps * amountStep.value;
};

// 拖动相关变量
let isDragging = false;
let startX = 0;
let startValue = 0;

// 开始拖动
const startDrag = (event) => {
  event.preventDefault();
  isDragging = true;
  
  // 记录起始位置和值
  startX = event.type === 'mousedown' ? event.clientX : event.touches[0].clientX;
  startValue = loanAmount.value;
  
  // 添加移动和结束事件监听
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('touchmove', handleDrag);
  document.addEventListener('mouseup', endDrag);
  document.addEventListener('touchend', endDrag);
};

// 处理拖动
const handleDrag = (event) => {
  if (!isDragging) return;
  
  const currentX = event.type === 'mousemove' ? event.clientX : event.touches[0].clientX;
  const sliderTrack = document.querySelector('.slider-track');
  if (!sliderTrack) return;
  
  const trackRect = sliderTrack.getBoundingClientRect();
  const trackWidth = trackRect.width;
  
  const deltaX = currentX - startX;
  const deltaPercentage = deltaX / trackWidth;
  const deltaValue = deltaPercentage * (maxAmount.value - minAmount.value);
  
  let newValue = startValue + deltaValue;
  
  // 按步长调整值
  const steps = Math.round((newValue - minAmount.value) / amountStep.value);
  newValue = minAmount.value + steps * amountStep.value;
  
  // 确保值在范围内
  newValue = Math.max(minAmount.value, Math.min(maxAmount.value, newValue));
  
  loanAmount.value = newValue;
};

// 结束拖动
const endDrag = () => {
  isDragging = false;
  
  // 移除事件监听
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('touchmove', handleDrag);
  document.removeEventListener('mouseup', endDrag);
  document.removeEventListener('touchend', endDrag);
};

// 选择期限
const selectPeriod = (period) => {
  selectedPeriod.value = period;
  console.log(`贷款期限已更改为: ${period}个月`);
};

// 显示服务协议
const showServiceAgreement = () => {
  agreementType.value = 'service';
  showAgreement.value = true;
};

// 显示借款协议
const showLoanAgreement = () => {
  agreementType.value = 'loan';
  showAgreement.value = true;
};

// 关闭协议
const closeAgreement = () => {
  showAgreement.value = false;
};

// 提交申请
const submitApplication = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  if (!agreePeriods.value) {
    ElMessage.warning('请您同意并勾选协议');
    return;
  }
  
  isSubmitting.value = true;
  //数据存入loanStore
  loanStore.setApplyData({
    amount: loanAmount.value,
    period: selectedPeriod.value
  });

  router.push('/loan/apply');
};

// 监听贷款金额和期限变化
watch([loanAmount, selectedPeriod], ([newAmount, newPeriod], [oldAmount, oldPeriod]) => {
  if (newAmount !== oldAmount) {
    console.log(`贷款金额已更改: ${formatAmount(oldAmount)} -> ${formatAmount(newAmount)}`);
  }
  
  if (newPeriod !== oldPeriod) {
    console.log(`贷款期限已更改: ${oldPeriod} -> ${newPeriod}个月`);
  }
  
  // 可以在这里添加其他逻辑，例如记录用户选择、发送统计数据等
});

// 生命周期钩子
onMounted(() => {
  // 初始化时加载数据
});

// 组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('touchmove', handleDrag);
  document.removeEventListener('mouseup', endDrag);
  document.removeEventListener('touchend', endDrag);
});
</script>

<style scoped lang="scss">
/* 确保页面可以滚动 */
:deep(html), :deep(body) {
  height: auto;
  overflow-y: auto;
}

.loan-home-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 60px; // 为底部导航留出空间
  overflow-y: auto;
  position: relative;
  width: 100%;
}

// 顶部区域
.header {
  .header-title {
    width: 100%;
    height: 50px;
    background-color: #3a4a6d;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 0 15px;
    
    span {
      font-size: 18px;
      color: #fff;
      font-weight: bold;
    }
  }
  
  .loan-info {
    background-color: #1e2a47;
    color: #fff;
    padding: 15px;
    text-align: center;
    
    .amount-label {
      font-size: 14px;
      color: #ccc;
      margin-bottom: 5px;
    }
    
    .amount-value {
      font-size: 42px;
      font-weight: bold;
      color: #f0c14b;
      margin-bottom: 15px;
    }
    
    .loan-features {
      display: flex;
      justify-content: space-around;
      
      .feature-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        font-size: 12px;
        color: #ccc;
        
        .el-icon {
          font-size: 20px;
          margin-bottom: 5px;
        }
      }
    }
  }
}

// 产品详情区域
.product-info {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  
  .info-item {
    flex: 1;
    text-align: center;
    
    .info-label {
      font-size: 14px;
      color: #999;
      margin-bottom: 5px;
    }
    
    .info-value {
      font-size: 16px;
      color: #333;
      
      .highlight {
        color: #f56c6c;
        font-weight: bold;
      }
      
      .original {
        color: #999;
        text-decoration: line-through;
        font-size: 12px;
        margin-left: 5px;
      }
    }
  }
}

// 申请金额区域
.apply-amount {
  background-color: #fff;
  padding: 20px 15px;
  margin-bottom: 10px;
  
  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 10px;
    text-align: center;
  }
  
  .amount-display {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .slider-container {
    position: relative;
    padding: 0 15px;
    margin-top: 30px;
    
    .min-amount, .max-amount {
      position: absolute;
      top: -20px;
      font-size: 12px;
      color: #999;
    }
    
    .min-amount {
      left: 15px;
    }
    
    .max-amount {
      right: 15px;
    }
    
    .slider-controls {
      display: flex;
      align-items: center;
      margin-top: 10px;
      
      .decrease-btn, .increase-btn {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        border: 1px solid #dcdfe6;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        
        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
      
      .slider-track {
        flex: 1;
        height: 6px;
        background-color: #e4e7ed;
        border-radius: 3px;
        margin: 0 15px;
        position: relative;
        cursor: pointer;
        
        .slider-fill {
          position: absolute;
          height: 100%;
          background-color: #3a4a6d;
          border-radius: 3px;
          left: 0;
          top: 0;
        }
        
        .slider-handle {
          position: absolute;
          width: 20px;
          height: 20px;
          background-color: #fff;
          border: 2px solid #3a4a6d;
          border-radius: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          cursor: grab;
          
          &:active {
            cursor: grabbing;
          }
          
          .handle-inner {
            width: 8px;
            height: 8px;
            background-color: #3a4a6d;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
      }
    }
  }
}

// 借款期限区域
.loan-period {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
    font-weight: normal;
  }
  
  .period-options {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    
    .period-btn {
      flex: 1;
      min-width: 60px;
      height: 40px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fff;
      color: #606266;
      font-size: 14px;
      cursor: pointer;
      
      &.active {
        background-color: #3a4a6d;
        color: #fff;
        border-color: #3a4a6d;
      }
    }
  }
}

// 每期还款区域
.repayment-info {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .section-title {
    font-size: 16px;
    color: #333;
    font-weight: normal;
  }
  
  .repayment-details {
    text-align: right;
    
    .repayment-amount {
      font-size: 16px;
      color: #333;
      margin-bottom: 5px;
      
      i {
        font-weight: bold;
        color: #f56c6c;
        font-style: normal;
      }
    }
    
    .repayment-rate {
      font-size: 12px;
      color: #999;
      
      #rixi, #fuwufei {
        color: #f56c6c;
        font-style: normal;
      }
    }
  }
}

// 协议同意区域
.agreement {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .agreement-checkbox {
    display: flex;
    align-items: center;
    
    a {
      color: #3a4a6d;
      text-decoration: none;
      margin: 0 2px;
    }
  }
}

// 申请按钮
.apply-btn-section {
  padding: 0 15px;
  margin-bottom: 15px;
  
  .apply-btn {
    width: 100%;
    height: 44px;
    background-color: #3a4a6d;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    
    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
}

// 成功案例滚动区域
.success-cases {
  background-color: #fff;
  padding: 10px 15px;
  margin-bottom: 10px;
  overflow: hidden;
  
  .marquee-container {
    height: 24px;
    overflow: hidden;
    position: relative;
    
    .marquee-content {
      position: absolute;
      animation: marquee-vertical 45s linear infinite;
      width: 100%;
      
      &:hover {
        animation-play-state: paused;
      }
    }
    
    .case-item {
      height: 24px;
      line-height: 24px;
      font-size: 14px;
      color: #606266;
      text-align: center;
      
      .case-date {
        color: #333;
      }
      
      .case-phone {
        color: #3a4a6d;
      }
      
      .case-amount {
        color: #f56c6c;
      }
    }
  }
}

@keyframes marquee-vertical {
  0% { transform: translateY(100%); }
  100% { transform: translateY(-100%); }
}

// 广告区域
.ad-section {
  padding: 0 15px;
  margin-bottom: 10px;
  
  .ad-item {
    margin-bottom: 10px;
    border-radius: 4px;
    overflow: hidden;
    
    .ad-placeholder {
      width: 100%;
      height: 80px;
      display: block;
      
      svg {
        display: block;
      }
    }
  }
}

// 常见问题区域
.faq-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .faq-item {
    margin-bottom: 15px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .faq-question {
      display: flex;
      align-items: center;
      margin-bottom: 5px;
      
      .question-tag {
        display: inline-block;
        width: 24px;
        height: 24px;
        background-color: #3a4a6d;
        color: #fff;
        border-radius: 4px;
        text-align: center;
        line-height: 24px;
        font-size: 12px;
        margin-right: 10px;
      }
      
      .question-text {
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }
    }
    
    .faq-answer {
      padding-left: 34px;
      font-size: 13px;
      color: #666;
      line-height: 1.5;
    }
  }
}

// 广告区域
.other {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
  text-align: center;
  
  #dnapp {
    display: block;
    
    .other-img {
      width: 90%;
      max-width: 300px;
      height: auto;
    }
  }
}

// 公司信息
.company-info {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 60px; // 为底部导航栏留出空间
  text-align: center;
  
  .info-text {
    font-size: 12px;
    color: #999;
    line-height: 1.8;
  }
}

// 协议弹窗
.agreement-content {
  max-height: 50vh;
  overflow-y: auto;
  
  h3 {
    font-size: 18px;
    color: #3a4a6d;
    margin-bottom: 15px;
  }
  
  p {
    margin-bottom: 10px;
    line-height: 1.6;
    color: #606266;
  }
}
</style>